import 'package:flutter/material.dart';
import 'package:flutter_again/models/video_info.dart';
import 'package:flutter_again/parsers/implementations/ptt_parser.dart';
import 'package:flutter_again/services/video_platform_manager.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import '../utils/log.dart';

class VideoPlayerPage extends StatefulWidget {
  const VideoPlayerPage({
    super.key,
    required this.title,
    required this.url,
    required this.platformId,
    this.num,
    this.seqLinks,
  });
  final String title;
  final String platformId;
  final String url;
  final List<VideoSeq>? seqLinks;
  final int? num;

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPage();
}

class _VideoPlayerPage extends State<VideoPlayerPage> {
  late VideoPlayerController _controller;
  final VideoPlatformManager platformManager = VideoPlatformManager()
    ..registerParser(PttParser());
  late ChewieController controller;
  String title = '';
  String url = '';
  int? num;
  List<VideoSeq>? seqLinks;

  String get displayTitle {
    return num != null ? '$title-第$num集' : title;
  }

  void toggleSeq(String url, String curNum) async {
    var videoUrl = await platformManager.getVideoUrl(
      widget.platformId,
      url,
    );
    log.d('视频页面接收到的视频url是：$videoUrl');
    if (videoUrl != null) {
      num = int.parse(curNum);
      url = videoUrl;
      controller.pause();
      controller.dispose();
      _controller.dispose();
      initVideo(videoUrl, seqLinks);
    }
  }

  void initVideo(String url, List<VideoSeq>? seqLinks) {
    log.d('loading videoUrl: $url');
    _controller = VideoPlayerController.networkUrl(Uri.parse(url))
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {});
      });
    controller = ChewieController(
      videoPlayerController: _controller,
      showSubtitles: true,
      additionalOptions: seqLinks != null
          ? (context) {
              return [
                OptionItem(
                  onTap: (context) {
                    showModalBottomSheet<void>(
                      context: context,
                      builder: (BuildContext context) {
                        return Container(
                          height: 200,
                          color: Colors.white,
                          child: ListView.builder(
                            itemCount: seqLinks.length,
                            itemBuilder: (context2, index) {
                              final item = seqLinks[index];
                              return TextButton(
                                child: Text(item.title),
                                onPressed: () {
                                  toggleSeq(item.url,  item.title);
                                  Navigator.of(context2).pop();
                                  Navigator.of(context).pop();
                                },
                              );
                            },
                          ),
                        );
                      },
                    );
                  },
                  iconData: Icons.looks_one,
                  title: '选择剧集',
                ),
              ];
            }
          : null,
    );
  }

  @override
  void initState() {
    super.initState();
    url = widget.url;
    seqLinks = widget.seqLinks;
    num = widget.num;
    title = widget.title;
    initVideo(widget.url, seqLinks);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(displayTitle)),
      body: Center(
        child: _controller.value.isInitialized
            ? Chewie(controller: controller)
            : Container(),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    _controller.dispose();
    super.dispose();
  }
}
